import React, {useEffect, useState} from 'react';
import '@chatui/core/dist/index.css';
import Sidebar from './components/Sidebar';
import ChatMain from './components/ChatMain';
import Login from './components/Login';
import axios from 'axios';

function App() {
    const [sessions, setSessions] = useState([]);
    const [currentSessionId, setCurrentSessionId] = useState(null);
    const [user, setUser] = useState(null);
    const [isLoading, setIsLoading] = useState(true);

    // 设置axios拦截器，自动添加token
    useEffect(() => {
        const token = localStorage.getItem('token');
        if (token) {
            axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
        }

        // 请求拦截器
        axios.interceptors.request.use(
            (config) => {
                const token = localStorage.getItem('token');
                if (token) {
                    config.headers.Authorization = `Bearer ${token}`;
                }
                return config;
            },
            (error) => {
                return Promise.reject(error);
            }
        );

        // 响应拦截器
        axios.interceptors.response.use(
            (response) => {
                return response;
            },
            (error) => {
                if (error.response?.status === 401) {
                    // token过期，清除本地存储并重新登录
                    localStorage.removeItem('token');
                    localStorage.removeItem('userInfo');
                    setUser(null);
                }
                return Promise.reject(error);
            }
        );
    }, []);

    // 检查用户登录状态
    useEffect(() => {
        const checkUserStatus = () => {
            const token = localStorage.getItem('token');
            const userInfo = localStorage.getItem('userInfo');

            if (token && userInfo) {
                try {
                    const parsedUserInfo = JSON.parse(userInfo);
                    setUser(parsedUserInfo);
                } catch (error) {
                    console.error('解析用户信息失败:', error);
                    localStorage.removeItem('token');
                    localStorage.removeItem('userInfo');
                }
            }
            setIsLoading(false);
        };

        checkUserStatus();
    }, []);

    // 获取会话列表
    const fetchSessions = async (preserveCurrentSession = false) => {
        try {
            const response = await axios.get('/api/xiaoyun/sessions');
            setSessions(response.data);

            // 如果没有当前会话且有会话列表，选择第一个
            // preserveCurrentSession为true时，不自动切换当前会话
            if (!preserveCurrentSession && !currentSessionId && response.data.length > 0) {
                setCurrentSessionId(response.data[0].sessionId);
            }
        } catch (error) {
            console.error('获取会话列表失败:', error);
        }
    };

    // 初始化会话
    const initializeSessions = async () => {
        try {
            const response = await axios.get('/api/xiaoyun/sessions');
            setSessions(response.data);

            if (response.data.length > 0) {
                setCurrentSessionId(response.data[0].sessionId);
            } else {
                // 如果没有任何会话，自动创建一个默认会话
                const newSession = await createNewSession(true);
                if (newSession) {
                    setSessions([newSession]);
                    setCurrentSessionId(newSession.sessionId);
                }
            }
        } catch (error) {
            console.error('初始化会话失败:', error);
        }
    };

    // 创建新会话
    const createNewSession = async (skipStateUpdate = false) => {
        try {
            const response = await axios.post('/api/xiaoyun/sessions', {});
            const newSession = response.data;

            // 重新获取会话列表，确保数据一致性
            await fetchSessions();
        } catch (error) {
            console.error('创建新会话失败:', error);
            return null;
        }
    };

    // 删除会话
    const deleteSession = async (sessionId) => {
        try {
            await axios.delete(`/api/xiaoyun/sessions/${sessionId}`);

            // 重新获取会话列表，确保数据一致性
            await fetchSessions();

            // 如果删除的是当前会话，切换到其他会话
            if (currentSessionId === sessionId) {
                const updatedSessions = sessions.filter(s => s.sessionId !== sessionId);
                setCurrentSessionId(updatedSessions.length > 0 ? updatedSessions[0].sessionId : null);
            }
        } catch (error) {
            console.error('删除会话失败:', error);
        }
    };

    // 重命名会话
    const renameSession = async (sessionId, newName) => {
        try {
            await axios.put(`/api/xiaoyun/sessions/${sessionId}`, {
                sessionName: newName
            });

            // 重新获取会话列表，确保数据一致性
            await fetchSessions(true); // 保持当前会话不被重置
        } catch (error) {
            console.error('重命名会话失败:', error);
        }
    };

    // 组件加载时初始化会话 - 只有用户登录后才初始化
    useEffect(() => {
        if (user) {
            initializeSessions();
        }
    }, [user]);

    // 处理用户登录
    const handleLogin = (userInfo) => {
        setUser(userInfo);
    };

    // 处理用户退出登录
    const handleLogout = () => {
        localStorage.removeItem('token');
        localStorage.removeItem('userInfo');
        setUser(null);
        setSessions([]);
        setCurrentSessionId(null);
    };

    // 如果正在加载，显示加载页面
    if (isLoading) {
        return (
            <div style={{
                height: '100vh',
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                background: '#FAF3E0'
            }}>
                <div>加载中...</div>
            </div>
        );
    }

    // 如果用户未登录，显示登录页面
    if (!user) {
        return <Login onLogin={handleLogin}/>;
    }

    return (
        <div style={{
            height: '100vh',
            background: '#FAF3E0', // 更换为流行的米白色
            display: 'flex',
            flexDirection: 'row'
        }}>
            <Sidebar
                sessions={sessions}
                currentSessionId={currentSessionId}
                onSessionSelect={setCurrentSessionId}
                onCreateSession={createNewSession}
                onDeleteSession={deleteSession}
                onRenameSession={renameSession}
                user={user}
                onLogout={handleLogout}
            />
            <ChatMain
                sessionId={currentSessionId}
                key={currentSessionId} // 强制重新渲染当切换会话时
            />
        </div>
    );
}

export default App;
